const path = require("path");
const fs = require("fs");
const colors = require("colors-console");
const utils = require("./utils");

const DS = ".DS_Store";
const MQ = "mengqi_";

/**
 * 递归寻找文件
 * @param {string} root 寻找路径
 * @param {string} findFile 目标文件名
 * @param {string} mod json,obj
 */
let dirWalk = function (root, findFile, mod = "obj") {
    let stat = fs.statSync(root);
    if (stat.isDirectory()) {
        //进入目录遍历目录下文件或路径
        let dirs = fs.readdirSync(root);
        //空路径停止递归
        if (dirs.length < 1) return null;
        for (let dir of dirs) {
            let subDir = path.join(root, dir);
            let cur = dirWalk(subDir, findFile);
            if (cur) {
                return cur;
            }
        }
    } else if (stat.isFile()) {
        let name = path.basename(root);
        if (name != DS && name === findFile) {
            console.log(colors("red", root));
            console.log(colors("green", "find: " + findFile));
            console.log(colors("blue", name), name === findFile);
            //TO DO:执行已经找到操作
            let text = fs.readFileSync(root, { encoding: "utf-8" });
            return mod == "obj" ? JSON.parse(text) : text;
        }
    }
    return null;
};

/**
 * 多文件名查找
 * @param {string} root
 * @param {string[]} files
 * @param {string} mod
 */
let dirWalkFiles = function (root, files, mod = "obj") {
    for (let file of files) {
        let result = dirWalk(root, file, mod);
        if (result) {
            return result;
        }
    }
    return null;
};

/**
 * 检测路径是否可以递归
 * @param {string} buildPath
 * @returns {boolean}
 */
let checkBuildAble = function (buildPath) {
    let pathObj = path.parse(buildPath);
    let stat = fs.statSync(buildPath);
    // console.log(colors('green', JSON.stringify(pathObj)));
    const dirName = pathObj.name;
    if (!stat.isDirectory()) {
        return false;
    } else if (dirName.search(MQ) < 0) {
        return false;
    }
    return true;
};

exports.dirWalk = dirWalk;
exports.checkBuildAble = checkBuildAble;
exports.dirWalkFiles = dirWalkFiles;
